<template>
  <div class="history-container">
    <aside>
<!--      <div class="input_section">-->
<!--        <el-input-->
<!--          placeholder="请输入内容"-->
<!--          clearable-->
<!--          v-model.trim="searchData"-->
<!--          prefix-icon="el-icon-search"-->
<!--          @input="getDeviceTree"-->
<!--        >-->
<!--          <el-button slot="append" @click="getDeviceTree">搜索</el-button>-->
<!--        </el-input>-->
<!--      </div>-->
      <el-scrollbar class="collapseSection" v-loading="isLoading">
        <el-menu
          default-active="2"
          @select="handleSelect"
          class="el-menu-vertical-demo">
          <el-menu-item :index="item.id" v-for="item in siteList" :key="item.id">
            <i class="el-icon-location-information"></i>
            <span slot="title">{{item.name}}</span>
          </el-menu-item>
        </el-menu>
      </el-scrollbar>
    </aside>
    <main>
      <div id="watchBox">
        <header>
          <span>监控视频-历史回放</span>
        </header>
        <!-- 监控视频区域 -->
        <div id="watchSection">
          <!--        <PlayerBox ref="PlayerHistoryRef" v-if="videoInfo.url" :url="videoInfo.url" :id="'player-history'"></PlayerBox>-->
          <el-empty description="" v-show="isBlock"></el-empty>
          <video
            id="play-videos"
            v-show="!isBlock"
            width="100%"
            height="100%"
            autoplay
            controls
            muted
          >
            <source :src="playUrl" type="video/mp4" />
          </video>
        </div>
        <!--        时间进度条-->
        <!--        <div class="time-scroll">-->
        <!--                <div class="time-s-box">-->
        <!--                  &lt;!&ndash; x轴 坐标刻度: 小时 &ndash;&gt;-->
        <!--                  <div class="hours">-->
        <!--                    <div class="item" v-for="(i, index) in hours" :key="index">-->
        <!--                      <span>{{ i }}:00</span>-->
        <!--                      &lt;!&ndash; <div class="rule" v-for="n in 3" :key="n"></div> &ndash;&gt;-->
        <!--                    </div>-->
        <!--                    <div class="item"><span>24:00</span></div>-->
        <!--                  </div>-->
        <!--                  &lt;!&ndash; 若有视频: 横向柱图 &ndash;&gt;-->
        <!--                  <div class="history-list" @mouseleave="showBar=false">-->
        <!--                    <div class="time-bar" v-show="showBar"><span></span></div>-->
        <!--                    <div class="item"-->
        <!--                         v-for="(i, index) in resultList"-->
        <!--                         :key="index"-->
        <!--                         @mousemove="historyMove($event)"-->
        <!--                         @mouseleave="showBar=false"-->
        <!--                         @click="playVideoTime(i, index, $event)"-->
        <!--                         :style="{left: i.left+'%', width: i.width+'%'}">-->
        <!--                      <div></div>-->
        <!--                    </div>-->
        <!--                  </div>-->
        <!--                </div>-->
        <!--              </div>-->
        <!--        /时间进度条-->
      </div>
      <div
        id="functionalArea"
        v-loading="downloading"
        element-loading-text="下载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <div class="datepicker">
          <Calendar v-show="siteId" :markDate="dateArr" @choseDay="chooseDay" @changeMonth="changeMonth" ref="calendar"></Calendar>
        </div>
        <div class="histroy-list">
          <div class="histroy-header">回放视频列表（{{ historyList.length }}段）</div>
          <el-scrollbar class="scrollbar-wrapper">
            <div
              v-for="(item, index) in historyList"
              :key="index"
              class="histroy-content"
              @click="playVideo(item.url)"
            >
              <div class="histroy-title">{{ item.createTime }}</div>
              <div class="histroy-info">
                <!--              <span class="info-left">播放时长:{{ item.times }}</span>-->
                <i
                  class="el-icon-download download"
                  @click.stop="downVideo(item.url, item.createTime)"
                ></i>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import Calendar from '@/components/datePicker/index.vue'
import _ from 'lodash'
import {
  getDateOfExistenceOfMedia,
  getDeviceHistoryFlvUrl,
  getDeviceTree
} from '@/service/monitor/video_surveillance/video_surveillance'
import { getSiteNameAndId } from '@/service/operate/site_manage/site_manage'

export default {
  name: 'VideoHistory',
  components: {
    Calendar
    // PlayerBox
  },
  props: {},
  data() {
    return {
      playUrl: '',
      timer: null,
      currentDay: '',
      isBlock: true,
      videoUrl: '',
      queryHistoryInfo: {
        startDate: '',
        endDate: ''
      },
      // 日历数据
      dateArr: [],
      hours: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22],
      // 时间轴数据
      resultList: [
        //   {
        //   end: 1637956793,
        //   left: 0,
        //   start: 1637942400,
        //   width: 16.658564814814813
        // }, {
        //   end: 1638028800,
        //   left: 37.53819444444444,
        //   start: 1637974833,
        //   width: 62.46180555555556
        // }
      ],
      showBar: false,
      // 历史内容列表
      historyList: [],
      searchData: '',
      // 设备数据
      deviceList: [],
      deviceId: '',
      isLoading: false,
      downloading: false,
      // 站点列表
      siteList: [],
      siteId: ''
    }
  },
  created() {
    this.getSiteList()
    this.setCurrentMonth()
  },
  mounted() {
  },
  watch: {
    searchData(newValue) {
      if (newValue === '') {
        this.getDeviceTree()
      }
    }
  },
  methods: {
    // 获取站点设备树
    getDeviceTree: _.throttle(async function() {
      if (this.isLoading) return
      this.isLoading = true
      const res = await getDeviceTree({
        keyword: this.searchData
      })
      this.isLoading = false
      if (res.code !== 0) return console.log(res.msg)
      this.deviceList = res.data
    }, 1000),
    // 选择设备
    handleCheckChange(data) {
      if (data.id) {
        this.deviceId = data.id
        // this.deviceId = '1470322215749132390'
        this.getDateOfExistenceOfMedia()
      }
    },
    // 设置本月
    setCurrentMonth() {
      // 如果为null,则格式化当前时间
      var value = Number(new Date())
      // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
      if (value.toString().length === 10) value *= 1000
      value = +new Date(Number(value))

      const targetTime = new Date(value)
      const year = targetTime.getFullYear()
      let month = targetTime.getMonth() + 1
      if (month < 10) {
        month = '0' + month
      }

      const yDate = new Date(year, month, 0)

      const startDateTime = year + '-' + month + '-' + '01' // 这个月第一天
      const endDateTime = year + '-' + month + '-' + yDate.getDate() // 这个月最后一天

      this.queryHistoryInfo.startDate = startDateTime
      this.queryHistoryInfo.endDate = endDateTime
    },
    // 获取时间列表
    async getDateOfExistenceOfMedia() {
      // this.historyList = []
      // console.log(this.queryHistoryInfo)
      const query = {
        siteId: this.siteId, // this.videoInfo.id
        startDate: this.queryHistoryInfo.startDate,
        endDate: this.queryHistoryInfo.endDate
      }
      const res = await getDateOfExistenceOfMedia(query)
      if (res.code !== 0) return console.log(res.msg)
      this.dateArr = res.data
      // console.log(res.data)
    },
    // 点击的日期
    chooseDay(day) {
      // console.log('选择日期', day)
      this.currentDay = day
      this.getCurrentDayList()
    },
    // 改变月份
    changeMonth(mouth) {
      // console.log('选择月份', mouth)
      this.queryHistoryInfo = mouth
      this.getDateOfExistenceOfMedia()
      this.historyList = []
      this.$refs.calendar.historyChose = []
    },
    // 鼠标在播放器的横向进度条 上移动触发
    historyMove(e) {
      let offset = ''
      if (e.target.className === '') {
        offset = e.target.parentElement.offsetLeft + e.offsetX
      } else if (e.target.className === 'item') {
        offset = e.target.offsetLeft + e.offsetX
      }
      const historyList = document.getElementsByClassName('history-list')[0]
      const sec = parseInt((offset / historyList.clientWidth) * 86400)
      const getTime = (val) => {
        let hour = parseInt(val / 3600)
        if (hour <= 9) hour = '0' + hour
        let min = parseInt(val / 60) % 60
        if (min <= 9) min = '0' + min
        let sec = val % 60
        if (sec <= 9) sec = '0' + sec
        return hour + ':' + min + ':' + sec
      }
      const time = getTime(sec)
      if (!this.showBar) this.showBar = true
      const timeBar = document.getElementsByClassName('time-bar')[0]
      timeBar.getElementsByTagName('span')[0].innerText = time
      timeBar.style.left = offset + 'px'
    },
    playVideoTime(i, index, event) {
      console.log('鼠标点击x轴i', i)
      console.log('鼠标点击x轴index', index)
      console.log('鼠标点击x轴event', event)
    },
    // 获取当前摄像头的录制日期
    async getCurrentDayList() {
      const res = await getDeviceHistoryFlvUrl({
        siteId: this.siteId,
        date: this.currentDay
      })
      if (res.code !== 0) return console.log(res.msg)
      this.historyList = res.data
    },
    playVideo(url) {
      const vdo = document.getElementById('play-videos')
      console.log(vdo)
      vdo.src = url
      vdo.play()
      // this.playUrl = url
      this.isBlock = false
    },
    downVideo(url, name) {
      const that = this
      this.downloading = true
      var xhr = new XMLHttpRequest()
      xhr.open('GET', url, true)
      xhr.responseType = 'arraybuffer'
      xhr.onload = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const blob = this.response
          // 转换一个blob链接
          const u = window.URL.createObjectURL(new Blob([blob], { type: 'video/mp4' }))
          const a = document.createElement('a')
          a.download = name
          a.href = u
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
          clearTimeout(that.timer)
        } else {
          that.$message.error('下载失败')
          // that.timer = setTimeout(() => {
          //   that.downVideo(url, name)
          // }, 1000)
        }
        that.downloading = false
      }
      xhr.send()
    },
    // 获取站点列表
    async getSiteList() {
      const res = await getSiteNameAndId()
      if (res.code !== 0) return
      this.siteList = res.data
    },
    handleSelect(key) {
      this.$refs.calendar.historyChose = []
      this.historyList = []
      this.siteId = key
      this.getDateOfExistenceOfMedia()
    }
  }
}
</script>

<style lang="less" scoped>
.history-container {
  display: flex;
  height: 790px;

  aside {
    width: 267px;

    .input_section {
      width: 267px;
      height: 62px;
      background-color: #f5faff;
    }

    .el-input {
      width: 235px;
      height: 36px;
      margin: 13px 16px;
      border: 1px solid #1585fc;
    }

    .el-input ::v-deep .el-input__inner {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
      border: 0;
    }

    .el-input ::v-deep .el-input-group__append {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
      color: #fff;
      background-color: #1585fc;
      cursor: pointer;
      border: 0;
    }

    .collapseSection {
      height: 700px;
    }
  }

  main {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  header {
    height: 60px;
    line-height: 60px;
    padding-left: 24px;
    border-bottom: 1px solid #dddddd;
  }

  #watchBox {
    width: 80%;

    .time-scroll {
      width: 100%;
      height: 55px;
      margin-bottom: 10px;
      position: relative;
      // padding-left: 30px;
      .time-s-box {
        width: 100%;
        height: 55px;
        position: relative;
        background: #fff;
      }

      .hours {
        width: 100%;
        position: absolute;
        bottom: 6px;
        display: flex;

        .item {
          flex: 1;
          height: 8px;
          border-right: 1px solid #b6b6b6;
          position: relative;
          border-radius: 1px;

          span {
            position: absolute;
            top: -24px;
            left: -30px;
            // z-index: 10;
            font-size: 12px;
            font-family: SimSun;
            font-weight: 400;
            color: #9298a7;
            width: 60px;
            text-align: center;
          }

          &:first-child {
            span {
              left: 0px;
              text-align: left;
            }
          }

          &:last-child {
            flex: 0;
            width: 0;
            border: 0;

            span {
              left: -3rem;
              text-align: right;
            }
          }

          // .rule {
          //   position: absolute;
          //   top: 0;
          //   height: 5px;
          //   border-left: 1px solid #777;
          //   left: 25%;
          // }
          // .rule:nth-child(2) {
          //   left: 50%;
          // }
          // .rule:nth-child(3) {
          //   left: 75%;
          // }
        }
      }

      .history-list {
        width: 100%;
        height: 22px;
        position: absolute;
        background: #efeff1;
        bottom: 14px;
        left: 0;

        .item {
          position: absolute;
          // height: 100%;
          height: 55px;
          bottom: -16px;

          div {
            position: absolute;
            width: 100%;
            height: 22px;
            bottom: 16px;
            background: #108cfd;
          }
        }
      }

      .time-bar {
        position: absolute;
        bottom: -16px;
        height: 55px;
        border-left: 3px solid #ff7275;

        span {
          position: absolute;
          left: 0px;
          top: -20px;
          font-size: 14px;
          font-family: SimSun;
          font-weight: bold;
          color: #ff7275;
        }
      }
    }
  }

  #watchSection {
    height: 650px;
    background-color: #dddddd;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  #functionalArea {
    width: 20%;
    padding-top: 2px;
    border-left: 1px solid #dddddd;

    .histroy-list {
      .histroy-header {
        height: 34px;
        background-color: #f5faff;
        font-size: 14px;
        font-weight: 600;
        padding-left: 16px;
        line-height: 34px;
      }

      .histroy-content {
        margin-top: 12px;
        background-color: #f5faff;
        padding: 16px;
        font-size: 14px;
        line-height: 14px;
        cursor: pointer;

        .histroy-info {
          margin-top: 5px;
          display: flex;
          justify-content: flex-end;

          .info-left {
          }

          .download {
            color: #1585fc;
            font-weight: 600;
            cursor: pointer;
          }
        }
      }
    }
  }

  .scrollbar-wrapper {
    height: 400px;
  }

  //隐藏x轴滚动
  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

.f18 {
  font-size: 18px;
}

video {
  object-fit: fill;
}
</style>
